package com.yuyang.wifi.jobservice;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.mine.LockScreenActivity;
import com.yuyang.wifi.receiver.AppReceiver;

import java.io.File;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class KeepAliveJobService extends JobService {


    private AppReceiver mLockScreenReceiver;
    private IntentFilter mIntentFilter = new IntentFilter();
    private IntentFilter mIntentFilterPackage = new IntentFilter();
    private RemoteViews remoteViews;


    @Override
    public boolean onStartJob(JobParameters params) {

        Log.i("KeepAliveJobService", "JobService onStartJob 开启");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 如果当前设备大于 7.0 , 延迟 5 秒 , 再次执行一次
            //Toast.makeText(getApplicationContext(), "KeepAliveJobService", Toast.LENGTH_LONG).show();
            startJob(this);
        }

        // 判定本地前台进程是否正在运行
//        boolean isLocalServiceRunning =
//                ServiceUtils.isServiceRunning(this, LocalForegroundService.class.getName());
//        if (!isLocalServiceRunning) {
//            startService(new Intent(this, LocalForegroundService.class));
//        }
//
//        // 判定远程前台进程是否正在运行
//        boolean isRemoteServiceRunning =
//                ServiceUtils.isServiceRunning(this, RemoteForegroundService.class.getName());
//        if (!isRemoteServiceRunning) {
//            startService(new Intent(this, RemoteForegroundService.class));
//        }

        Log.e("TAG", "MyApplication===KeepAliveJobService广播创建了");

        mIntentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
        mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
        mIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        mIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        mIntentFilter.addAction(Intent.ACTION_USER_PRESENT);
        mIntentFilter.addAction("android.net.wifi.supplicant.CONNECTION_CHANGE");

        //package广播
        mIntentFilterPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
        mIntentFilterPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
        mIntentFilterPackage.addDataScheme("package");

        // 设置广播的优先级为最大
        mIntentFilter.setPriority(Integer.MAX_VALUE);
        mIntentFilterPackage.setPriority(Integer.MAX_VALUE);

        if (null == mLockScreenReceiver) {
            mLockScreenReceiver = new AppReceiver();
            //mLockScreenReceiver.setType(1);
            mIntentFilter.setPriority(Integer.MAX_VALUE);
            mIntentFilterPackage.setPriority(Integer.MAX_VALUE);
            registerReceiver(mLockScreenReceiver, mIntentFilter);
            registerReceiver(mLockScreenReceiver, mIntentFilterPackage);
            //Toast.makeText(getApplicationContext(), "AppService", Toast.LENGTH_LONG).show();
        }

        String ID = "com.yuyang.wifi";    //这里的id里面输入自己的项目的包的路径
        String NAME = "Channel One";
        NotificationCompat.Builder builder;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(ID, NAME, manager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(KeepAliveJobService.this).setChannelId(ID);
            remoteViews = new RemoteViews(getPackageName(), R.layout.notification_custom_layout);
            builder.setCustomContentView(remoteViews);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        builder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);
        builder.setTicker(" ");
        builder.setAutoCancel(false);
        builder.setCustomContentView(remoteViews);
        //builder.setSound(null);
        builder.setNotificationSilent();
        builder.setPriority(NotificationCompat.PRIORITY_MIN);
//        builder.setContentTitle("手机管家持续保护");
//        builder.setContentText(" ");
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_hide));
        builder.setSmallIcon(R.mipmap.ic_launcher_hide);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, LockScreenActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
        }
        Notification n = builder.build();
        // 通知栏显示系统图标
        startForeground(0x111, n);
        //stopForeground(true);
        return false;
    }

//    public void notificationPlayVideo() {
//        Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/mysound.mp3");
//        //Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);//类型通知
//        Ringtone rt = RingtoneManager.getRingtone(getApplicationContext(), uri);
//        rt.play();
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLockScreenReceiver != null) {
            unregisterReceiver(mLockScreenReceiver);
            mLockScreenReceiver = null;
        }
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i("KeepAliveJobService", "JobService onStopJob 关闭");
        if (mLockScreenReceiver != null) {
            unregisterReceiver(mLockScreenReceiver);
            mLockScreenReceiver = null;
        }
        return false;
    }

    public static void startJob(Context context) {
        // 创建 JobScheduler
        JobScheduler jobScheduler =
                (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

        // 第一个参数指定任务 ID
        // 第二个参数指定任务在哪个组件中执行
        // setPersisted 方法需要 android.permission.RECEIVE_BOOT_COMPLETED 权限
        // setPersisted 方法作用是设备重启后 , 依然执行 JobScheduler 定时任务
        JobInfo.Builder jobInfoBuilder = new JobInfo.Builder(10,
                new ComponentName(context.getPackageName(), KeepAliveJobService.class.getName()))
                .setPersisted(true);

        // 7.0 以下的版本, 可以每隔 5000 毫秒执行一次任务
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            jobInfoBuilder.setPeriodic(5_000);

        } else {
            // 7.0 以上的版本 , 设置延迟 5 秒执行
            // 该时间不能小于 JobInfo.getMinLatencyMillis 方法获取的最小值
            jobInfoBuilder.setMinimumLatency(5_000);
        }

        // 开启定时任务
        jobScheduler.schedule(jobInfoBuilder.build());

    }
}
